<template>

  <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="150px">
    <el-card>

      <el-row :gutter="20">

        <el-col :span="12">
          <el-form-item label="试题类型 " prop="quType">
            <dic-list-select v-model="postForm.quType" :disabled="update" :excludes="excludeTypes" dic-code="qu_type" title="请选择题型" />
          </el-form-item>
        </el-col>

        <el-col v-if="!child" :span="12">
          <el-form-item label="所属题库" prop="repoId">
            <repo-select v-model="postForm.repoId" />
          </el-form-item>
        </el-col>

        <el-col v-if="!child" :span="12">
          <el-form-item label="难度等级 " prop="level">
            <dic-list-select v-model="postForm.level" dic-code="qu_level" title="请选择难度等级" />
          </el-form-item>
        </el-col>
        <el-col v-if="!child" :span="12">
          <el-form-item label="所属章节">
            <chapter-select v-model="postForm.chapterId" :repo-id="postForm.repoId" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="试题内容" prop="content">
            <Tinymce ref="content" v-model="postForm.content" :height="200" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="整题解析" prop="oriPrice">
            <Tinymce ref="analysis" v-model="postForm.analysis" :height="200" />
          </el-form-item>
        </el-col>
      </el-row>

      <div v-if="postForm.quType && postForm.quType!=='4' && postForm.quType!=='6' && postForm.quType!=='99'" class="filter-container" style="margin-top: 25px">

        <el-button :disabled="postForm.answerList.length >= 8 || (postForm.quType==='3' && postForm.answerList.length>=2)" class="filter-item" type="primary" icon="el-icon-plus" size="small" plain @click="handleAdd">
          添加选项
        </el-button>

        <el-table
          :data="postForm.answerList"
          :border="true"
          row-key="id"
          style="width: 100%;"
        >
          <el-table-column
            v-if="itemIsAnswer"
            label="是否答案"
            width="100"
            align="center"
          >
            <template v-slot="scope">
              <el-checkbox v-model="scope.row.isRight" @change="answerChange(scope.$index)">答案</el-checkbox>
            </template>

          </el-table-column>

          <el-table-column
            v-if="itemImage"
            label="选项图片"
            width="120px"
            align="center"
          >
            <template v-slot="scope">

              <file-upload
                v-model="scope.row.image"
              />

            </template>
          </el-table-column>

          <el-table-column
            label="选项内容"
          >
            <template v-slot="scope">
              <el-input v-model="scope.row.content" :placeholder="postForm.quType==='5'?'填空题支持多个近似答案用||隔开，如：10||十，学员填写`10`或者`十`都判为正确':'输入选项内容'" size="small" type="textarea" />
            </template>
          </el-table-column>

          <el-table-column
            v-if="itemAnalysis"
            label="选项解析"
          >
            <template v-slot="scope">
              <el-input v-model="scope.row.analysis" size="small" type="textarea" />
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="100px"
          >
            <template v-slot="scope">
              <el-button type="danger" icon="el-icon-delete" circle @click="removeItem(scope.$index, $event)" />
            </template>
          </el-table-column>

        </el-table>

        <div v-if="postForm.quType==='5'" style="margin-top: 10px">
          <el-checkbox v-model="postForm.answerOrder" label="严格按序作答"/>
        </div>

      </div>

    </el-card>

  </el-form>
</template>

<script>
import ChapterSelect from '@/components/ChapterSelect'
import DicListSelect from '@/components/DicListSelect'
import FileUpload from '@/components/FileUpload'
import Tinymce from '@/components/Tinymce'
import RepoSelect from '@/components/RepoSelect'

export default {
  name: 'QuItemSave',
  components: { RepoSelect, Tinymce, FileUpload, DicListSelect, ChapterSelect },
  props: {
    value: Object,
    child: {
      type: Boolean,
      default: false
    },
    update: Boolean,
    excludeTypes: Array
  },
  data() {
    return {

      initContent: false,
      initAnalysis: false,

      // 不同题型的显示项目
      itemImage: true,
      itemAnalysis: true,
      itemIsAnswer: true,

      // 初始化表单数据
      postForm: {
        quType: '',
        repoId: '',
        answerList: []
      },
      rules: {
        content: [
          { required: true, message: '试题内容不能为空！' }
        ],

        quType: [
          { required: true, message: '试题类型不能为空！' }
        ],

        level: [
          { required: true, message: '必须选择难度等级！' }
        ],

        repoId: [
          { required: true, message: '请选择题库！' }
        ]
      }
    }
  },
  watch: {
    value: {
      handler(val) {
        this.postForm = val
        this.initValue(false)
      },
      deep: true
    },

    // 变换题型
    'postForm.quType': {
      handler(val) {
        // 添加模式允许改题型
        if (!this.update) {
          this.handleTypeChange(val)
        }
      }
    },
    postForm: {
      handler(val) {
        this.$emit('input', val)
        this.$emit('change', val)
      },
      deep: true
    }
  },

  created() {
    this.postForm = this.value
    // 初始化
    this.$nextTick(() => {
      setTimeout(() => {
        this.initValue(true)
      }, 1000)
    })
  },
  methods: {

    // 添加时选择题型做对应的智能填充
    handleTypeChange(v) {
      // 填空题和组合题
      if (v === '5' || v === '99') {
        this.itemImage = false
        this.itemAnalysis = false
        this.itemIsAnswer = false
      } else {
        this.itemImage = true
        this.itemAnalysis = true
        this.itemIsAnswer = true
      }

      // 清空并填充
      this.postForm.answerList = []
      if (v === '3') {
        this.postForm.answerList.push({ isRight: true, content: '正确', analysis: '' })
        this.postForm.answerList.push({ isRight: false, content: '错误', analysis: '' })
      }

      // 单选多选默认增加3个
      if (v === '1' || v === '2') {
        for (let i = 0; i < 3; i++) {
          this.postForm.answerList.push({ isRight: false, content: '', analysis: '' })
        }
      }

      if (v === '5') {
        for (let i = 0; i < 2; i++) {
          this.postForm.answerList.push({ isRight: false, content: '', analysis: '' })
        }
      }
    },

    // 添加子项
    handleAdd() {
      this.postForm.answerList.push({ isRight: false, content: '', analysis: '' })
    },

    // 添加连线分组
    handleAddGroup() {
      this.postForm.answerGroup.push([{ isRight: true, content: '' }, { isRight: true, content: '' }])
    },

    removeItem(index) {
      this.postForm.answerList.splice(index, 1)
    },

    initValue(init) {
      // 填空题不需要那些东西
      if (this.postForm.quType === '5') {
        this.itemImage = false
        this.itemAnalysis = false
        this.itemIsAnswer = false
      } else {
        this.itemImage = true
        this.itemAnalysis = true
        this.itemIsAnswer = true
      }

      // 首次初始化
      if (init) {
        // 填充内容 - 格式化JSON内容或综合显示题目信息
        if (this.$refs.content) {
          const formattedContent = this.formatCompleteQuestionContent()
          this.$refs.content.setContent(formattedContent)
        }

        if (this.$refs.analysis) {
          this.$refs.analysis.setContent(this.postForm.analysis)
        }
      }
    },

    // 综合格式化试题完整内容（包括分散在不同字段的数据）
    formatCompleteQuestionContent() {
      // 首先尝试使用JSON格式化
      if (this.postForm.content && this.postForm.content.trim().startsWith('{')) {
        const jsonFormatted = this.formatQuestionContent(this.postForm.content);
        if (jsonFormatted && jsonFormatted !== this.postForm.content) {
          return jsonFormatted;
        }
      }
      
      // 如果不是JSON或JSON格式化失败，则综合各字段数据
      let formattedText = '';
      
      // 添加题干
      if (this.postForm.content) {
        formattedText += `<p><strong>问题：</strong>${this.postForm.content}</p>`;
      }
      
      // 根据题型添加答案选项
      if (this.postForm.answerList && this.postForm.answerList.length > 0) {
        // 判断题 (quType === '3')
        if (this.postForm.quType === '3') {
          const correctAnswer = this.postForm.answerList.find(item => item.isRight);
          if (correctAnswer) {
            formattedText += `<p><strong>答案：</strong>${correctAnswer.content}</p>`;
          }
        }
        // 选择题 (quType === '1' 单选, quType === '2' 多选)
        else if (this.postForm.quType === '1' || this.postForm.quType === '2') {
          formattedText += `<p><strong>选项：</strong></p><ul>`;
          this.postForm.answerList.forEach((option, index) => {
            const label = String.fromCharCode(65 + index); // A, B, C, D...
            formattedText += `<li>${label}. ${option.content}</li>`;
          });
          formattedText += `</ul>`;
          
          const correctAnswers = this.postForm.answerList.filter(item => item.isRight);
          if (correctAnswers.length > 0) {
            const answerText = correctAnswers.map((item, index) => {
              const answerIndex = this.postForm.answerList.indexOf(item);
              const label = String.fromCharCode(65 + answerIndex);
              return `${label}. ${item.content}`;
            }).join(', ');
            formattedText += `<p><strong>正确答案：</strong>${answerText}</p>`;
          }
        }
        // 填空题 (quType === '5')
        else if (this.postForm.quType === '5') {
          const answers = this.postForm.answerList.map(item => item.content).filter(content => content);
          if (answers.length > 0) {
            formattedText += `<p><strong>参考答案：</strong>${answers.join('、')}</p>`;
          }
        }
      }
      
      return formattedText || this.postForm.content || '';
    },

    // 格式化试题内容JSON为友好显示格式
    formatQuestionContent(content) {
      if (!content) {
        return '';
      }
      
      // 如果内容以{开头，说明是JSON格式，需要进行格式化
      if (content.trim().startsWith('{')) {
        try {
          const parsedContent = JSON.parse(content);
          
          // 检查是否包含question字段
          if (parsedContent.question) {
            let formattedText = '';
            
            // 添加问题部分
            formattedText += `<p><strong>问题：</strong>${parsedContent.question}</p>`;
            
            // 根据题型添加不同的内容
            // 选择题：包含choose数组
            if (parsedContent.choose && Array.isArray(parsedContent.choose)) {
              formattedText += `<p><strong>选项：</strong></p><ul>`;
              parsedContent.choose.forEach(option => {
                formattedText += `<li>${option}</li>`;
              });
              formattedText += `</ul>`;
              
              if (parsedContent.answer) {
                formattedText += `<p><strong>正确答案：</strong>${parsedContent.answer}</p>`;
              }
            }
            // 判断题：答案为布尔值或布尔字符串
            else if (typeof parsedContent.answer === 'boolean' || 
                     parsedContent.answer === 'true' || 
                     parsedContent.answer === 'false' ||
                     parsedContent.answer === '1' ||
                     parsedContent.answer === '0') {
              let isCorrect = false;
              if (typeof parsedContent.answer === 'boolean') {
                isCorrect = parsedContent.answer;
              } else if (parsedContent.answer === 'true' || parsedContent.answer === '1') {
                isCorrect = true;
              } else {
                isCorrect = false;
              }
              formattedText += `<p><strong>答案：</strong>${isCorrect ? '正确' : '错误'}</p>`;
            }
            // 填空题：答案为数组
            else if (Array.isArray(parsedContent.answer)) {
              formattedText += `<p><strong>参考答案：</strong>${parsedContent.answer.join('、')}</p>`;
            }
            // 简答题或其他：答案为字符串
            else if (parsedContent.answer) {
              formattedText += `<p><strong>答案：</strong>${parsedContent.answer}</p>`;
            }
            
            return formattedText;
          }
        } catch (e) {
          // JSON解析失败，直接返回原始内容
          return content;
        }
      }
      
      // 如果不是JSON格式，直接返回原始内容
      return content;
    },

    // 单选题互斥不选定多个
    answerChange(index, e) {
      // 类型
      if (this.postForm && (this.postForm.quType === '1' || this.postForm.quType === '3')) {
        for (let i = 0; i < this.postForm.answerList.length; i++) {
          if (index !== i) {
            this.postForm.answerList[i].isRight = false
          }
        }
      }
    },

    // 同步获得验证结果
    async validate() {
      const valid = await this.$refs.postForm.validate().catch((err) => { return err })
      return valid
    },

    // 清理内容
    clear() {
      const quType = this.postForm.quType
      const repoId = this.postForm.repoId
      const level = this.postForm.level
      const chapterId = this.postForm.chapterId

      this.postForm = {
        quType: quType,
        repoId: repoId,
        level: level,
        chapterId: chapterId,
        answerList: [],
        subList: []
      }

      // 重新选择一下
      this.handleTypeChange(quType)

      // 填充内容
      if (this.$refs.content) {
        this.$refs.content.setContent('')
      }

      if (this.$refs.analysis) {
        this.$refs.analysis.setContent('')
      }
    }

  }
}
</script>

